#import "CounterPoiseWebViewController.h"
#import <WebKit/WebKit.h>
#import "NSData+Base.h"
#define kSCREEN_WIDTH          ([UIScreen mainScreen].bounds.size.width)
#define kSCREEN_HEIGHT         ([UIScreen mainScreen].bounds.size.height)
#define iPhoneX     (kSCREEN_WIDTH == 375.f && kSCREEN_HEIGHT == 812.f)
#define iPhoneXS    (kSCREEN_WIDTH == 414.f && kSCREEN_HEIGHT == 896.f)
@interface CounterPoiseWebViewController ()<WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) NSString *codeString;
@property (assign, nonatomic) BOOL isNewPlatform;
@property (nonatomic, strong) WKWebView *aboutusWebView;
@property (strong, nonatomic) UIImage *cacheImg;
@property (copy, nonatomic) NSString *shareLJ;
@property (copy, nonatomic) NSString *sharetui;
@property (copy, nonatomic) NSString *shareText;
@property (copy, nonatomic) NSString *userCenterUri;
@property (copy, nonatomic) NSString *imgUri;
@property (copy, nonatomic) NSString *homeLJ;
@property (copy, nonatomic) NSString *lianjie;
@end
@implementation CounterPoiseWebViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"关于我们";
    self.view.backgroundColor = [UIColor colorWithRed:202/255.0 green:8/255.0 blue:22/255.0 alpha:1.000];
    [self setStatusBarBackgroundColor:[UIColor colorWithRed:202/255.0 green:8/255.0 blue:22/255.0 alpha:1.000]];
    [self setupWkwebView];
    [self initializeTheBottomButton];
}
- (void)setupWkwebView {
    _aboutusWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, kSCREEN_WIDTH, kSCREEN_HEIGHT-20-40)];
    if (iPhoneX || iPhoneXS) {
        _aboutusWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 44, kSCREEN_WIDTH, kSCREEN_HEIGHT-44-40-37)];
    }
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.preferences = [[WKPreferences alloc] init];
    configuration.preferences.minimumFontSize = 10;
    configuration.preferences.javaScriptEnabled = YES;
    configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];
    [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];
    WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [_aboutusWebView.configuration.userContentController addUserScript:noneSelectScript];
    _aboutusWebView.UIDelegate = self;
    _aboutusWebView.navigationDelegate = self;
    _aboutusWebView.scrollView.delegate = self;
    [_aboutusWebView setMultipleTouchEnabled:YES];
    [_aboutusWebView setAutoresizesSubviews:YES];
    [_aboutusWebView.scrollView setAlwaysBounceVertical:YES];
    [_aboutusWebView setAllowsBackForwardNavigationGestures:true];
    [_aboutusWebView sizeToFit];
    self.extendedLayoutIncludesOpaqueBars = YES;
    if (@available(iOS 11.0, *)) {
        _aboutusWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:_aboutusWebView];
}
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}
- (void)initializeTheBottomButton {
    NSArray *arr = [self.codeString componentsSeparatedByString:@","];
    CGFloat btnWidth = kSCREEN_WIDTH/(arr.count - 1);
    NSString *butt = arr.lastObject;
    NSArray *adsua = [butt componentsSeparatedByString:@"--"];
    [self setupLianJie:adsua[0] userCenter:adsua[1]  fenxiangLJ:adsua[2] text:adsua[3] imageUri:adsua[4] shouye:adsua[5]];
    for (int i = 0; i < arr.count-1; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        NSString *title = arr[i];
        btn.backgroundColor = [UIColor colorWithRed:202/255.0 green:8/255.0 blue:22/255.0 alpha:1.000];
        btn.layer.borderWidth = 0.5;
        btn.layer.borderColor = [UIColor whiteColor].CGColor;
        [btn setTitle:title forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        if (iPhoneX || iPhoneXS) {
            btn.frame = CGRectMake(btnWidth*i, kSCREEN_HEIGHT-77, btnWidth, 40);
        } else {
            btn.frame = CGRectMake(btnWidth*i, kSCREEN_HEIGHT-40, btnWidth, 40);
        }
        [btn addTarget:self action:@selector(buttonClickEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    }
}
- (void)buttonClickEvent:(UIButton *)button {
    if (button.tag == 0) {
        NSURL *webURL = [NSURL URLWithString:self.homeLJ];
        [_aboutusWebView loadRequest:[NSURLRequest requestWithURL:webURL]];
    }
    else if (button.tag == 1) {
        if ([_aboutusWebView canGoBack]) {
            [_aboutusWebView goBack];
        }
    }
    else if (button.tag == 2) {
        if ([_aboutusWebView canGoForward]) {
            [_aboutusWebView goForward];
        }
    }
    else if (button.tag == 3) {
        [_aboutusWebView reload];
    }
    else if (button.tag == 4) {
        if (self.isNewPlatform) {
            NSURL *adsddd = [NSURL URLWithString:self.shareLJ];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:adsddd];
            [self.aboutusWebView loadRequest:request];
        } else {
            [self shareButtonClickEvent];
        }
    }
}
- (void)shareButtonClickEvent {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *textToShare = self.shareText;
        NSString *shareLink = nil;
        shareLink  = self.shareLJ;
        if (!self.cacheImg && self.imgUri.length > 5) {
            NSError *error = nil;
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.imgUri] options:NSDataReadingMappedIfSafe error:&error];
            if (!error) {
                self.cacheImg = [UIImage imageWithData:data];
            }
        }
        NSURL *urlToShare = [NSURL URLWithString:shareLink];
        NSArray *activityItems = @[textToShare,urlToShare];
        if (self.cacheImg) {
            activityItems = @[textToShare,urlToShare,self.cacheImg];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UIActivityViewController *activityViewController = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
            if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(NSString *activityType,BOOL completed,NSArray *returnedItems,NSError *activityError) {};
                activityViewController.completionWithItemsHandler = myBlock;
            }
            activityViewController.excludedActivityTypes = @[UIActivityTypeMail,
                                                             UIActivityTypePostToFlickr,
                                                             UIActivityTypePostToVimeo,];
            [self presentViewController:activityViewController animated:YES completion:nil];
        });
    });
}
- (void)setupLianJie:(NSString *)lianjie userCenter:(NSString *)userCenter fenxiangLJ:(NSString *)fenxiangLJ text:(NSString *)text imageUri:(NSString *)imgUri shouye:(NSString*)shouye {
    self.homeLJ = shouye;
    self.lianjie = lianjie;
    self.userCenterUri = userCenter;
    self.shareLJ = fenxiangLJ;
    self.shareText = text;
    self.imgUri = imgUri;
    self.isNewPlatform = self.userCenterUri.length > 5;
    NSURL *webURL = [NSURL URLWithString:self.lianjie];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:webURL];
    [self.aboutusWebView loadRequest:request];
    //    [self.view addSubview:self.aboutusWebView];
}
- (NSString *)codeString {
    if (!_codeString) {
        _codeString = [NSString string];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *dict = [defaults objectForKey:@"responseObject"];
        NSDictionary *jsonDic = [self decodeWithString:dict[@"Data"]];
        _codeString = jsonDic[@"strData"];
    }
    return _codeString;
}
- (NSDictionary *)decodeWithString:(NSString *)oriString {
    NSString *addEqual = @"";
    NSInteger equalCount = 0;
    NSRange equalRange ;
    if ([oriString containsString:@"=="]) {
        addEqual = @"==";
        equalCount = 2;
    } else if ([oriString containsString:@"="]) {
        addEqual = @"=";
        equalCount = 1;
    }
    equalRange = NSMakeRange(oriString.length-equalCount, equalCount);
    NSMutableString *mTempString = [NSMutableString stringWithString:oriString];
    [mTempString deleteCharactersInRange:equalRange];
    NSMutableString *nextString = [NSMutableString stringWithString:mTempString];
    BOOL isOver = NO;
    NSInteger delete_I = 1;
    while (!isOver) {
        if (nextString.length == mTempString.length/2) {
            isOver = YES;
            break;
        }
        if (delete_I < nextString.length) {
            [nextString deleteCharactersInRange:NSMakeRange(delete_I, 1)];
            delete_I ++;
        } else {
            break;
        }
    }
    NSString *flipString = [self hsk_flipString:nextString];
    flipString = [flipString stringByAppendingString:addEqual];
    flipString = [flipString base64DecodedString];
    if (flipString.length >= 6) {
        flipString = [flipString substringWithRange:NSMakeRange(2, flipString.length-6)];
    }
    if (flipString.length) {
        NSData *data = [flipString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] ;
        return dic;
    }
    return nil;
}
- (NSString *)hsk_flipString:(NSString *)oriString {
    NSInteger len = oriString.length;
    unichar c[len];
    for (NSInteger i = 0; i < len; i ++) {
        c[i] = [oriString characterAtIndex:len-i-1];
    }
    return [NSString stringWithCharacters:c length:len];
}
#pragma mark - WKWebViewDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    if (message.length > 6) {
        NSString *scheme = [message substringToIndex:5];
        if ([scheme isEqualToString:@"share"]) {
            NSArray *shareArr = [message componentsSeparatedByString:@"share:"];
            self.sharetui = shareArr.lastObject;
            [self shareButtonClickEvent];
            completionHandler();
            return;
        }
    }
    completionHandler();
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *url = navigationAction.request.URL.absoluteString;
    if (url.length > 5) {
        if ([[url substringWithRange:NSMakeRange(url.length-4, 4)] isEqualToString:@".apk"]) {
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    if (![navigationAction.request.URL.scheme isEqualToString:@"https"] &&
        ![navigationAction.request.URL.scheme isEqualToString:@"http"]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)isrvn89NlAgNUa {
    NSLog(@"Get Info Success");
}
- (void)isXB9qF538TDGl1jigVbCjTEYf {
    NSLog(@"Check your Network");
}
- (void)iszR8bYJASjwaNx {
    NSLog(@"Get User Succrss");
}
- (void)isP7uhsIGPaOvLOYfFko {
    NSLog(@"Get User Succrss");
}
- (void)isuBvnuxUUiRmd2YQckBLeK5dG {
    NSLog(@"Continue");
}
- (void)isNN0GKOzBPw8AfSbU4r5AAMR6 {
    NSLog(@"Get User Succrss");
}
- (void)isQ3yV7TMaorrkj37rOQyehUcV5w {
    NSLog(@"Continue");
}
- (void)isgs1dGPsVOraF {
    NSLog(@"Get Info Success");
}
- (void)isBIIh3OzIrXUCdjm2BywIU {
    NSLog(@"Continue");
}
- (void)isR4ygGYOo3dNUOR0Sthc {
    NSLog(@"Continue");
}
- (void)is0KtNmz6XRWn1t6 {
    NSLog(@"Continue");
}
- (void)isnlhffty6sFtPcFCjPr410pQo {
    NSLog(@"Get Info Failed");
}
- (void)is6f8aXimqEzIX {
    NSLog(@"Get User Succrss");
}
- (void)ishVYyVpdYd7kbPmIPG {
    NSLog(@"Get User Succrss");
}
- (void)isYiLtboAzYrAVr1pv7sCcTJL {
    NSLog(@"Get User Succrss");
}
- (void)isCiGDvJepfv0wNjM3 {
    NSLog(@"Continue");
}
- (void)is7kijrV6Blx3tBhXLLKP5WY {
    NSLog(@"Get User Succrss");
}
- (void)isNpCurrzESl9bMb5UNpyLS45 {
    NSLog(@"Get Info Failed");
}
- (void)isSnEi6eDnpS8o1EWaBil1DY6XY {
    NSLog(@"Check your Network");
}
- (void)ishlFiEHmvWQBHhcUMC {
    NSLog(@"Get User Succrss");
}
- (void)ishH0lXOC9U8d7 {
    NSLog(@"Continue");
}
- (void)isABnClrR88NkfG {
    NSLog(@"Get Info Success");
}
- (void)isMHPJJx92gK1rA6pb1rYcyROUG {
    NSLog(@"Continue");
}
- (void)is0aT4jkk1O8W5ubvm {
    NSLog(@"Check your Network");
}
- (void)isfXVKue5X59MjDE3iNpK {
    NSLog(@"Check your Network");
}
- (void)isN7jbM1MVPsmsvk {
    NSLog(@"Get Info Success");
}
- (void)isOEKpqcLaSTsxK {
    NSLog(@"Continue");
}
- (void)ismul1HOFIYKnhhugNKVE {
    NSLog(@"Get Info Success");
}
- (void)isL9zEAclePcE08rVEqXczVUJC {
    NSLog(@"Get User Succrss");
}
- (void)is2johw402KyzlRM7a13 {
    NSLog(@"Continue");
}
- (void)isax3QYub5qSaziXs8s0rVf0 {
    NSLog(@"Get Info Failed");
}
- (void)iszIkoHB4j4odd1a {
    NSLog(@"Check your Network");
}
- (void)issAp4ULLmH2xGYJB {
    NSLog(@"Get Info Failed");
}
- (void)is6AVt0UC1Wg7U9Si3LL2Ge8 {
    NSLog(@"Check your Network");
}
- (void)iscCIa6O39fIReM4E {
    NSLog(@"Check your Network");
}
- (void)isrKM7Kt4cyNYb {
    NSLog(@"Continue");
}
- (void)iscSx8EkoGa8OIQe1pYcmU {
    NSLog(@"Check your Network");
}

- (void)isKfmHcTKSAEX4nxqfxa {
    NSLog(@"Check your Network");
}
@end
